package org.txazo.blog.util;

import org.txazo.blog.util.md5.MD5;

/**
 * 密码工具类
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-10
 */
public class PasswdUtil {

	/**
	 * 生成密钥
	 * 
	 * @param email 邮箱
	 * @return 密钥
	 */
	public static String getCipherKey(String email) {
		if (StringUtil.isNotEmpty(email)) {
			String cipherKey = MD5.md5OfHex(email);
			char[] cipherKeys = new char[4];
			for (int i = 0; i < 16;) {
				cipherKeys[i / 4] = cipherKey.charAt(i);
				i += 4;
			}
			return String.valueOf(cipherKeys);
		}
		return null;
	}

	/**
	 * 生成密文
	 * 
	 * @param password 密码
	 * @param cipherKey 密钥
	 * @return 密文
	 */
	public static String getCipherText(String password, String cipherKey) {
		if (StringUtil.isNotEmpty(password) && StringUtil.isNotEmpty(cipherKey)) {
			return MD5.md5OfHex(password + cipherKey);
		}
		return null;
	}

	/**
	 * 登录验证
	 * 
	 * @param password 密码
	 * @param cipherText 密文
	 * @param cipherKey 密钥
	 * @return true | false
	 */
	public static boolean loginValidate(String password, String cipherText,
			String cipherKey) {
		if (StringUtil.isNotEmpty(password)
				&& StringUtil.isNotEmpty(cipherText)
				&& StringUtil.isNotEmpty(cipherKey)) {
			return getCipherText(password, cipherKey).equals(cipherText);
		}
		return true;
	}

	public static void main(String[] args) {
		System.out.println("用户邮箱：784990655@qq.com");
		System.out.println("用户密钥：" + getCipherKey("784990655@qq.com"));
		System.out.println("用户密码：txazo");
		System.out.println("用户密文：" + getCipherText("txazo", "6FFE"));
		System.out.println("用户登录："
				+ (loginValidate("txazo", "3572B40EB5343C59", "6FFE") ? "成功"
						: "失败"));
	}

}
